package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表
 */

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map data = new HashMap();
        List<String> months = new ArrayList();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);//2018-12-10
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//2019-1-10
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        data.put("months", months);

        List<Integer> memberCount = memberService.findMemberCountByMonths(months);

        data.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);
    }

    @RequestMapping("/getMemberReportByDate")
    public Result getMemberReportByDate(String date) {
        //获取起始日期和结束日期
        String[] dateSplit = date.split(",");
        String start = dateSplit[0];
        String end = dateSplit[1];

        //获取起始年份和结束年份
        String[] startSplit = start.split("\\.");
        String[] endSplit = end.split("\\.");
        String startYear = startSplit[0];
        String endYear = endSplit[0];
        int startYeari = Integer.parseInt(startYear);
        int endYeari = Integer.parseInt(endYear);

        //获取int类型起始月份和结束月份以及差值
        String startMonth = startSplit[1];
        String endMonth = endSplit[1];
        int startMonthi = Integer.parseInt(startMonth);
        int endMonthi = Integer.parseInt(endMonth);
        int month = endMonthi - startMonthi;

        //获取日历类，设置map和list集合存储数据
        Calendar calendar = Calendar.getInstance();
        Map data = new HashMap();
        List<String> months = new ArrayList();

        //设定规则，判断日期年份月份是否超出当前时间，是否低于2019年，
        if (startYeari < 2019 || endYeari > calendar.get(Calendar.YEAR) || endMonthi > calendar.get(Calendar.MONTH) + 1) {
            return new Result(false, MessageConstant.GET_MEMBER_FAIL);
        }

        //遍历month，存入list集合，获取折线图x轴时间段
        for (int i = 0; i <= month; i++){
            calendar.set(Calendar.MONTH, startMonthi - 1);//2019-1-10
            startMonthi += 1;
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        data.put("months", months);

        //调用service层，查询时间段内会员数量
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        data.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);
    }

    //为男女饼形图建立方法
    @RequestMapping("/getMemberReportPieSex")
    public Result getMemberReportPieSex(){
//        假数据
//        Map map=new HashMap();
//        List<String> setmemberNames=new ArrayList<>();
//        setmemberNames.add("男");
//        setmemberNames.add("女");
//        map.put("setmemberNames",setmemberNames);
//        List<Map<String,Object>> setmemberCount=new ArrayList<>();
//        Map map1=new HashMap();
//        map1.put("name","男");
//        map1.put("value",100);
//        Map map2=new HashMap();
//        map2.put("name","女");
//        map2.put("value",200);
//        setmemberCount.add(map1);
//        setmemberCount.add(map2);
//        map.put("setmemberCount",setmemberCount);
//
//        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);

        List<Map<String,Object>> setmemberCount =memberService.findMemberCountBySex();
        List<String> setmemberNames=new ArrayList<>();
        for (Map<String,Object> map:setmemberCount
             ) {
            String name = (String) map.get("name");
            setmemberNames.add(name);
        }
        Map map=new HashMap();
        map.put("setmemberNames",setmemberNames);
        map.put("setmemberCount",setmemberCount);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    //为  年龄饼形图建立方法
    @RequestMapping("/getMemberReportPieAge")
    public  Result getMemberReportPieAge(){
//                假数据
//        Map map=new HashMap();
//        List<String> setmemberNames=new ArrayList<>();
//        setmemberNames.add("0-18");
//        setmemberNames.add("18-40");
//        setmemberNames.add("40-80");
//        setmemberNames.add("大于80");
//        map.put("setmemberNames",setmemberNames);
//        List<Map<String,Object>> setmemberCount=new ArrayList<>();
//        Map map1=new HashMap();
//        map1.put("name","0-18");
//        map1.put("value",4);
//        Map map2=new HashMap();
//        map2.put("name","18-40");
//        map2.put("value",20);
//        Map map3=new HashMap();
//        map3.put("name","40-80");
//                         男/女
//        map3.put("value",10);
//                        count计算
//        Map map4=new HashMap();
//        map4.put("name","大于80");
//        map4.put("value",30);
//        setmemberCount.add(map1);
//        setmemberCount.add(map2);
//        setmemberCount.add(map3);
//        setmemberCount.add(map4);
//        map.put("setmemberCount",setmemberCount);
//        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);

        List<Map<String,Object>> setmemberCount=memberService.findMemberCountByAge();
        List<String> setmemberNames=new ArrayList<>();
        for (Map<String,Object> map:setmemberCount
        ) {
            String name = (String) map.get("name");
            setmemberNames.add(name);
        }
        Map map=new HashMap();
        map.put("setmemberNames",setmemberNames);
        map.put("setmemberCount",setmemberCount);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    //查询套餐预约占比数据统计
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        /*Map map = new HashMap();
        List<String> setmealNames = new ArrayList<>();
        setmealNames.add("直接访问");
        setmealNames.add("邮件营销");
        map.put("setmealNames",setmealNames);

        List<Map<String,Object>> setmealCount = new ArrayList();
        Map map1 = new HashMap();
        map1.put("name","直接访问");
        map1.put("value",100);

        Map map2 = new HashMap();
        map2.put("name","邮件营销");
        map2.put("value",200);

        setmealCount.add(map1);
        setmealCount.add(map2);
        map.put("setmealCount",setmealCount);

        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);*/


        List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }

        Map map = new HashMap();
        map.put("setmealNames", setmealNames);
        map.put("setmealCount", setmealCount);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    @Reference
    private ReportService reportService;

    //获取运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> map = null;
        try {
            map = reportService.getBusinessReport();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
    }

    //运营数据报表导出
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = null;
        try {
            //调用Service获取运营数据
            result = reportService.getBusinessReport();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //使用POI将查询到的数据写入到Excel文件中
            String templateDirPath = request.getSession().getServletContext().getRealPath("template");
            String filePath = templateDirPath + File.separator + "report_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个Sheet工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int num = 12;
            //热门套餐
            for (Map map : hotSetmeal) {
                row = sheet.getRow(num++);
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
